package world.ztomorrow.author.interceptor;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import world.ztomorrow.author.dto.AuthorInfoDto;
import world.ztomorrow.author.service.impl.AuthorServiceImpl;
import world.ztomorrow.common.constant.ErrorCodeEnum;
import world.ztomorrow.common.exception.BusinessException;
import world.ztomorrow.common.utils.UserHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@RequiredArgsConstructor
public class AuthorInterceptor implements HandlerInterceptor {

    private final AuthorServiceImpl authorService;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        Long userId = UserHolder.getUserId();
        AuthorInfoDto author = authorService.getAuthor(userId);

        if (author == null) {
            throw new BusinessException(ErrorCodeEnum.USER_UN_AUTH);
        }
        UserHolder.setAuthorId(author.getId());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        UserHolder.clear();
    }
}
